package grpc

import (
	"context"

	msg "gitee.com/flycash/simple-im/api/proto/gen/message/v1"
	"gitee.com/flycash/simple-im/internal/domain"
	"gitee.com/flycash/simple-im/internal/service"
	msgv1 "gitee.com/flycash/ws-gateway/api/proto/gen/gatewayapi/v1"
	"google.golang.org/protobuf/encoding/protojson"
)

const (
	defaultBizID int64 = 1
)

type MsgServer struct {
	msgv1.UnimplementedBackendServiceServer
	svc service.MessageService
}

func NewMsgServer(svc service.MessageService) *MsgServer {
	return &MsgServer{
		svc: svc,
	}
}

func (m *MsgServer) OnReceive(ctx context.Context, request *msgv1.OnReceiveRequest) (*msgv1.OnReceiveResponse, error) {
	protoMsg := &msg.ImMessage{}
	if err := protojson.Unmarshal(request.GetBody(), protoMsg); err != nil {
		return nil, err
	}

	// 转换为 domain 对象
	domainMsg := convertProtoToDomain(protoMsg)

	// 处理消息
	id, err := m.svc.Send(ctx, domainMsg)
	if err != nil {
		return nil, err
	}

	return &msgv1.OnReceiveResponse{
		MsgId: id,
		BizId: defaultBizID,
	}, nil
}

func convertProtoToDomain(protoMsg *msg.ImMessage) domain.Message {
	return domain.Message{
		Key:         protoMsg.Key,
		ContentType: protoMsg.ContentType,
		Content:     protoMsg.Content,
		Cid:         protoMsg.Cid,
		Sender:      protoMsg.Sender,
		SendTime:    protoMsg.SendTime,
	}
}
